package action

import (
	"strings"

	"gitee.com/sansaniot/ssiot-core/logger"
	"gorm.io/gorm"

	"ssdevice/common/enums"
	"ssdevice/common/middleware/mqtt"
	"ssdevice/common/utils"
	"ssdevice/internal/device/models"
)

type Props struct {
	Orm *gorm.DB
}

func (action *Props) Execute(topic string, jsonData map[string]interface{}) {
	devSn := strings.Split(topic, "/")[3]
	_, to := AutoLogin(action.Orm, devSn, jsonData)
	if strings.HasSuffix(topic, "/props") {
		targetSn := utils.If(len(to) > 0 && to != devSn, to, devSn).(string)
		system := utils.GetFieldFromJson([]string{"data", "system"}, jsonData)
		now := utils.GetNowTimeStr()
		if system != nil {
			mqtt.DealData(targetSn, system.(map[string]interface{}), func(sData map[string]interface{}) {
				action.systemUpdate(targetSn, sData, now)
			}, enums.SystemMsg)
		}
		// 更新dev状态
		UpdateLiveStatus(action.Orm, devSn, to, now)
	}
}

// 系统参数system更新
func (action *Props) systemUpdate(devSn string, system map[string]interface{}, now string) {
	if len(system) == 0 {
		return
	}
	devSystem := &models.SysDevSystem{}
	devSystem.Model.Orm = action.Orm
	if err := devSystem.UpdateDevSystem(devSn, system); err != nil {
		logger.Error(err)
		return
	}
	addHistoryQueue(devSn, system, enums.SystemMsg, now)
}
